package com.xyht.sca_s.student_manage_system.modules.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.SmsUserView;
import com.xyht.sca_s.student_manage_system.modules.inform.entity.vo.SmsExamineUserInfoVo;
import com.xyht.sca_s.student_manage_system.modules.inform.mapper.SmsUserViewMapper;
import com.xyht.sca_s.student_manage_system.modules.news.constant.CollectStatusConstant;
import com.xyht.sca_s.student_manage_system.modules.news.constant.LikesStatusConstant;
import com.xyht.sca_s.student_manage_system.modules.news.entity.SmsNews;
import com.xyht.sca_s.student_manage_system.modules.news.entity.SmsNewsInformCollect;
import com.xyht.sca_s.student_manage_system.modules.news.entity.SmsNewsInformLikes;
import com.xyht.sca_s.student_manage_system.modules.news.entity.dto.SmsNewsAddDto;
import com.xyht.sca_s.student_manage_system.modules.news.entity.dto.SmsNewsIdDto;
import com.xyht.sca_s.student_manage_system.modules.news.entity.dto.SmsNewsUpdateDto;
import com.xyht.sca_s.student_manage_system.modules.news.entity.vo.SmsNewsDetailBlackVo;
import com.xyht.sca_s.student_manage_system.modules.news.entity.vo.SmsNewsDetailVo;
import com.xyht.sca_s.student_manage_system.modules.news.mapper.SmsNewsInformCollectMapper;
import com.xyht.sca_s.student_manage_system.modules.news.mapper.SmsNewsInformLikesMapper;
import com.xyht.sca_s.student_manage_system.modules.news.mapper.SmsNewsMapper;
import com.xyht.sca_s.student_manage_system.modules.news.service.SmsNewsService;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.common.util.TimeUtil.StringtoDate;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-12-08
 */
@Service
public class SmsNewsServiceImpl extends ServiceImpl<SmsNewsMapper, SmsNews> implements SmsNewsService {

    @Autowired
    private SmsNewsMapper smsNewsMapper;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private SmsNewsInformLikesMapper smsUserLikesMapper;
    @Autowired
    private SmsNewsInformCollectMapper smsNewsInformCollectMapper;
    @Autowired
    private SmsUserViewMapper smsUserViewMapper;
    @Autowired
    private CacheUtil cacheUtil;
    @Override
    public ResponseResult addNews(SmsNewsAddDto smsNewsAddDto, String newsId) {
        //校验参数是否为空
        if (isNullOrEmpty(smsNewsAddDto.getNewsTopic()) || isNullOrEmpty(smsNewsAddDto.getEventType())
                || isNullOrEmpty(smsNewsAddDto.getNewsContent())
                || isNullOrEmpty(smsNewsAddDto.getNewsType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //开始赋值
        SmsNews smsNew = new SmsNews();
        BeanUtils.copyProperties(smsNewsAddDto,smsNew);
        smsNew.setStartTime(new Date());
        smsNew.setCreateTime(new Date());
        //赋值发布人就是登陆者
        smsNew.setNewsId(newsId);
        smsNewsMapper.insert(smsNew);
        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteNews(SmsNews smsNews) {
        //查询是否存在该新闻
        if(smsNews.getId() == null){
            return CommonResult.failed(CommonCodeEnum.NEWS_NOT_EXIST);
        }
        int result = smsNewsMapper.deleteById(smsNews.getId());
        //删除失败
        if(result == 0){
            return CommonResult.failed(CommonCodeEnum.DELETE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateNews(SmsNewsUpdateDto smsNewsUpdateDto,String newsId) {
        //修改的新闻不存在
        if(smsNewsUpdateDto.getId()==null){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查询数据库中的通知
        SmsNews smsNew = smsNewsMapper.selectById(smsNewsUpdateDto.getId());
        if (smsNew == null) {
            log.debug("通知不存在,修改失败");
            return CommonResult.failed(CommonCodeEnum.NEWS_NOT_EXIST);
        }
        SmsNews smsNews = new SmsNews();
        //赋值修改
        BeanUtils.copyProperties(smsNewsUpdateDto,smsNews);
        smsNews.setUpdateTime(new Date());
        smsNews.setNewsId(newsId);
        smsNew.setCreateTime(smsNew.getCreateTime());
        int result = smsNewsMapper.updateById(smsNews);
        //修改失败
        if(result==0){
            return CommonResult.failed(CommonCodeEnum.UPDATE_FAIL);
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getNewsById(String id,String viewNewsId) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsNews smsNews = smsNewsMapper.selectById(id);
        if (smsNews == null) {
            log.debug("查询失败,新闻不存在");
            return CommonResult.failed(CommonCodeEnum.NEWS_NOT_EXIST);
        }
        if(smsNews.getEndTime()!=null){
            if(smsNews.getEndTime().compareTo(new Date()) < 0 ){
                return CommonResult.failed(CommonCodeEnum.NEWS_TIME_EXPIRED);
            }
        }


        SmsNewsDetailVo smsNewsDetailVo = new SmsNewsDetailVo();
        BeanUtils.copyProperties(smsNews, smsNewsDetailVo);

        //浏览人保存
        SmsUserView smsUserView = new SmsUserView();
        smsUserView.setViewUserId(viewNewsId);
        smsUserView.setViewObjectId(id);
        smsUserView.setCreateTime(new Date());
        smsUserViewMapper.insert(smsUserView);
        //回显浏览人
        List<SmsExamineUserInfoVo> smsExamineUserInfoVos = new ArrayList<>();
        QueryWrapper<SmsUserView> smsUserViewQueryWrapper = new QueryWrapper<>();
        smsUserViewQueryWrapper
                .select("DISTINCT view_user_id");
        smsUserViewQueryWrapper.lambda().eq(SmsUserView::getViewObjectId,id);
        List<SmsUserView> smsUserViews = smsUserViewMapper.selectList(smsUserViewQueryWrapper);
        for (SmsUserView userView : smsUserViews) {
            SmsExamineUserInfoVo smsExamineUserInfoVo = new SmsExamineUserInfoVo();
            SmsUser smsUser = cacheUtil.getUserInfo(userView.getViewUserId());
            if (!isNullOrEmpty(smsUser)) {
                smsExamineUserInfoVo.setUsername(smsUser.getUsername());
                smsExamineUserInfoVo.setUserPic(smsUser.getUserPic());
                smsExamineUserInfoVo.setRealName(smsUser.getRealName());
                smsExamineUserInfoVo.setId(smsUser.getId());
                smsExamineUserInfoVos.add(smsExamineUserInfoVo);
            }
        }
        smsNewsDetailVo.setSmsExamineUserVo(smsExamineUserInfoVos);
        //浏览量
        QueryWrapper<SmsUserView> smsViewCountQueryWrapper = new QueryWrapper<>();
        smsViewCountQueryWrapper.lambda().eq(SmsUserView::getViewObjectId,id);
        Integer viewCount = smsUserViewMapper.selectCount(smsViewCountQueryWrapper);
        smsNewsDetailVo.setViewCount(viewCount);

        //点赞和收藏状态
        QueryWrapper<SmsNewsInformLikes> smsUserLikesQueryWrapper = new QueryWrapper<>();
        smsUserLikesQueryWrapper.lambda().eq(SmsNewsInformLikes::getLikeUserId, viewNewsId)
                .and(i -> i.eq(SmsNewsInformLikes::getInfoId, id));
        SmsNewsInformLikes smsNewsInformLikes = smsUserLikesMapper.selectOne(smsUserLikesQueryWrapper);
        if(!isNullOrEmpty(smsNewsInformLikes)){
            smsNewsDetailVo.setLikesStatus(smsNewsInformLikes.getStatus());
        }else {
            smsNewsDetailVo.setLikesStatus(LikesStatusConstant.LIKES_STATUS_CANCEL);
        }
        QueryWrapper<SmsNewsInformCollect> smsUserCollectQueryWrapper = new QueryWrapper<>();
        smsUserCollectQueryWrapper.lambda().eq(SmsNewsInformCollect::getCollectUserId, viewNewsId)
                .and(i -> i.eq(SmsNewsInformCollect::getCollectInfoId, id));
        SmsNewsInformCollect smsNewsInformCollect = smsNewsInformCollectMapper.selectOne(smsUserCollectQueryWrapper);
        if(!isNullOrEmpty(smsNewsInformCollect)){
            smsNewsDetailVo.setCollectStatus(smsNewsInformCollect.getCollectStatus());
        }else {
            smsNewsDetailVo.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_CANCEL);
        }
        String userName = smsNewsMapper.selectUserNameById(smsNews.getNewsId());
        if(userName == null){
            userName = "用户+account";
        }

        //发布人的头像
        SmsUser smsUser = smsUserMapper.selectById(smsNews.getNewsId());
        smsNewsDetailVo.setIssuerFace(smsUser.getUserPic());
        smsNewsDetailVo.setNewsId(userName);
        smsNewsDetailVo.setIsRead("1");
        return CommonResult.success(smsNewsDetailVo);
    }

    @Override
    public ResponseResult getAllNews(String newsId,Integer pageSize,Integer pageNum,
                                     String type, String search, String beginTime, String endTime) {
        if(isNullOrEmpty(newsId)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<SmsNews> queryWrapper = new QueryWrapper<>();
        List<SmsNewsDetailBlackVo> smsNewsDetailBlackVos =new ArrayList<>();
        List<SmsNews> smsNews = smsNewsMapper.selectList(queryWrapper);
        if (smsNews == null) {
            return CommonResult.failed(CommonCodeEnum.INFORM_NOT_EXIST);
        }
        Page<SmsNews> page = new Page<>(pageNum,pageSize);
        queryWrapper.lambda().orderByDesc(SmsNews::getCreateTime);
        if(!isNullOrEmpty(type)){
            queryWrapper.lambda().eq(SmsNews::getNewsType,type);
        }
        if(!isNullOrEmpty(search)){
            queryWrapper.lambda().like(SmsNews::getNewsTopic,search);
        }
        if(!isNullOrEmpty(beginTime)){
            Date bgTime = StringtoDate(beginTime);
            queryWrapper.lambda().ge(SmsNews::getStartTime,bgTime);
        }
        if(!isNullOrEmpty(endTime)){
            Date edTime = StringtoDate(endTime);
            queryWrapper.lambda().le(SmsNews::getStartTime,edTime);
        }
        smsNewsMapper.selectPage(page,queryWrapper);
        List<SmsNews> list = page.getRecords();
        for (SmsNews news :list){
            SmsNewsDetailBlackVo smsNewsDetailBlackVo = new SmsNewsDetailBlackVo();
            BeanUtils.copyProperties(news,smsNewsDetailBlackVo);
            if(news.getEndTime()!=null){
                //判断是否过期
                if(news.getEndTime().compareTo(new Date()) < 0){
                    //过期
                    smsNewsDetailBlackVo.setState("0");
                }else {
                    //有效
                    smsNewsDetailBlackVo.setState("1");
                }
            }
            String userName = smsNewsMapper.selectUserNameById(news.getNewsId());
            if(userName == null){
                userName = "用户+account";
            }

            //发布人的头像
            SmsUser smsUser = smsUserMapper.selectById(news.getNewsId());
            smsNewsDetailBlackVo.setIssuerFace(smsUser.getUserPic());

            smsNewsDetailBlackVo.setNewsId(userName);
            smsNewsDetailBlackVos.add(smsNewsDetailBlackVo);
        }
        int total = (int)page.getTotal();
        return CommonResult.success(smsNewsDetailBlackVos,total);
    }

    @Override
    public ResponseResult getAllStudentNews(String newsId, String newsType, Integer pageSize, Integer pageNum) {

        if(isNullOrEmpty(newsId)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        Page<SmsNews> page = new Page<>(pageNum,pageSize);
        QueryWrapper<SmsNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .gt(SmsNews::getEndTime,new Date())
                .orderByDesc(SmsNews::getCreateTime);

        if(!isNullOrEmpty(newsType)){
            queryWrapper.lambda().eq(SmsNews::getNewsType, newsType);
        }
        smsNewsMapper.selectPage(page,queryWrapper);
        int total = (int)page.getTotal();
        List<SmsNews> list = page.getRecords();
        List<SmsNewsDetailVo> smsNewsDetailVos =new ArrayList<>();
        for (SmsNews smsNew : list) {
            //判断是否过期
            if (smsNew.getEndTime() != null) {
                if (smsNew.getEndTime().compareTo(new Date()) < 0) {
                    //过期
                    continue;
                }
            }

            SmsNewsDetailVo smsNewsDetailVo = new SmsNewsDetailVo();
            String userName = smsNewsMapper.selectUserNameById(smsNew.getNewsId());
            if (userName == null) {
                userName = "用户+account";
            }
            BeanUtils.copyProperties(smsNew, smsNewsDetailVo);
            //赋值登录的姓名
            smsNewsDetailVo.setNewsId(userName);
            //发布人的头像
            SmsUser smsUser = smsUserMapper.selectById(smsNew.getNewsId());
            if (!isNullOrEmpty(smsUser)) {
                smsNewsDetailVo.setIssuerFace(smsUser.getUserPic());
            }
            smsNewsDetailVos.add(smsNewsDetailVo);
        }
        return CommonResult.success(smsNewsDetailVos, total);
    }

    @Override
    @Transactional
    public ResponseResult likes(String likeUserId, SmsNewsIdDto newsId) {
        if(isNullOrEmpty(likeUserId)){
            return CommonResult.failed(CommonCodeEnum.UNAUTHORIZED);
        }
        SmsNews smsNews = smsNewsMapper.selectById(newsId.getId());
        if(isNullOrEmpty(smsNews)){
            return CommonResult.failed(CommonCodeEnum.NEWS_NOT_EXIST);
        }

        //历史数据未设置点赞数处理
        if(smsNews.getLikes() == null){
            smsNews.setLikes(0);
        }
        //根据新闻id和用户id查数据
        QueryWrapper<SmsNewsInformLikes> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsNewsInformLikes::getLikeUserId, likeUserId)
                .and(i -> i.eq(SmsNewsInformLikes::getInfoId, newsId.getId()));
        SmsNewsInformLikes userLikes = smsUserLikesMapper.selectOne(queryWrapper);
        //如果不存在数据则,则点赞,状态设置为1,新增数据并点赞数+1
        if(userLikes == null){
            SmsNewsInformLikes smsNewsInformLikes = new SmsNewsInformLikes();
            smsNewsInformLikes.setLikeUserId(likeUserId);
            smsNewsInformLikes.setInfoId(newsId.getId());
            smsNewsInformLikes.setSign(0);
            smsNewsInformLikes.setStatus(LikesStatusConstant.LIKES_STATUS_LIKES);
            smsNewsInformLikes.setCreateTime(new Date());
            smsUserLikesMapper.insert(smsNewsInformLikes);
            smsNews.setLikes(smsNews.getLikes() + 1);
            smsNewsMapper.updateById(smsNews);
            return CommonResult.success(LikesStatusConstant.LIKES_STATUS_LIKES);
        }
        //1.如果存在数据,查看状态,
        //1.1状态为1,则取消点赞,点赞数-1.
        if(userLikes.getStatus() == 1){
            //赞数-1
            if(smsNews.getLikes() != null && smsNews.getLikes() != 0) {
                smsNews.setLikes(smsNews.getLikes() - 1);
            }
            userLikes.setStatus(LikesStatusConstant.LIKES_STATUS_CANCEL);
            smsUserLikesMapper.updateById(userLikes);
            smsNewsMapper.updateById(smsNews);
            return CommonResult.success(LikesStatusConstant.LIKES_STATUS_CANCEL);
        }
        //1.2状态为0,则点赞,点赞数+1.
        if(userLikes.getStatus() == 0){
            //赞数+1
            smsNews.setLikes(smsNews.getLikes() + 1);
            smsNewsMapper.updateById(smsNews);
            //
            userLikes.setStatus(LikesStatusConstant.LIKES_STATUS_LIKES);
            smsUserLikesMapper.updateById(userLikes);
        }
        return CommonResult.success(LikesStatusConstant.LIKES_STATUS_LIKES);
    }

    @Override
    @Transactional
    public ResponseResult collect(String collectUserId, SmsNewsIdDto newsId) {
        if(isNullOrEmpty(collectUserId)){
            return CommonResult.failed(CommonCodeEnum.UNAUTHORIZED);
        }
        SmsNews smsNews = smsNewsMapper.selectById(newsId.getId());
        if(isNullOrEmpty(smsNews)){
            return CommonResult.failed(CommonCodeEnum.NEWS_NOT_EXIST);
        }
        //历史数据未设置收藏数处理
        if(smsNews.getCollect() == null){
            smsNews.setCollect(0);
        }
        //根据新闻id和用户id查数据
        QueryWrapper<SmsNewsInformCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsNewsInformCollect::getCollectUserId, collectUserId)
                .and(i -> i.eq(SmsNewsInformCollect::getCollectInfoId, newsId.getId()));
        SmsNewsInformCollect userCollect = smsNewsInformCollectMapper.selectOne(queryWrapper);
        //如果不存在数据则,则收藏,状态设置为1,新增数据,收藏+1
        if(userCollect == null){
            SmsNewsInformCollect smsNewsInformCollect = new SmsNewsInformCollect();
            smsNewsInformCollect.setCollectUserId(collectUserId);
            smsNewsInformCollect.setCollectInfoId(newsId.getId());
            smsNewsInformCollect.setSign(0);
            smsNewsInformCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_COLLECT);
            smsNewsInformCollect.setCreateTime(new Date());
            smsNewsInformCollectMapper.insert(smsNewsInformCollect);
            smsNews.setCollect(smsNews.getCollect() + 1);
            smsNewsMapper.updateById(smsNews);
            return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_COLLECT);
        }
        //1.如果存在数据,查看状态,
        //1.1状态为1,则取消收藏,收藏数-1.
        if(userCollect.getCollectStatus() == 1){
            //收藏数-1
            if(smsNews.getCollect() != null && smsNews.getCollect() != 0) {
                smsNews.setCollect(smsNews.getCollect() - 1);
            }
            userCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_CANCEL);
            smsNewsInformCollectMapper.updateById(userCollect);
            smsNewsMapper.updateById(smsNews);
            return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_CANCEL);
        }
        //1.2状态为0,则收藏,收藏数+1.
        if(userCollect.getCollectStatus() == 0){
            //收藏数+1
            smsNews.setCollect(smsNews.getCollect() + 1);
            smsNewsMapper.updateById(smsNews);
            userCollect.setCollectStatus(CollectStatusConstant.COLLECT_STATUS_COLLECT);
            smsNewsInformCollectMapper.updateById(userCollect);
        }
        return CommonResult.success(CollectStatusConstant.COLLECT_STATUS_COLLECT);
    }

}
